package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class DishServiceimpl extends ServiceImpl<DishMapper,Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Override
    /**
     * 新增菜品，同时保存口味数据
     */
    @Transactional
    public void saveFlavor(DishDto dishDto) {
        //保存菜品的基本信息，到菜品表
        this.save(dishDto);
        Long id = dishDto.getId();//菜品ID
        List<DishFlavor> flavors = dishDto.getFlavors();
//        flavors.stream().map((ipo)->{
//            ipo.setDishId(id);
//            return ipo;
//        });
//        flavors.forEach((listid)->{
//            listid.setDishId(id);
//        });
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(id);
        }

        dishFlavorService.saveBatch(flavors);
    }


    /**
     * 回显，根据ID查询菜品信息和口味信息
     * @param id
     * @return
     */
    @Override
    public DishDto get(Long id) {
        //查询菜品基本信息
        Dish byId = this.getById(id);

        log.info(byId.toString());
        //创建DishDto对象
        DishDto dishDto = new DishDto();

        //将Dish表中的菜品ID查询出来，拷贝给dishDto表
        BeanUtils.copyProperties(byId,dishDto);

        //查询菜品口味信息,从口味表DishFlavor表查询
        LambdaQueryWrapper<DishFlavor> lfqw = new LambdaQueryWrapper<>();

        //添加条件查询口味表中的菜品ID。
        lfqw.eq(DishFlavor::getDishId,byId);

        //调用dishFlavorService菜品Service方法将筛选后的条件数据放入集合中
        List<DishFlavor> list = dishFlavorService.list(lfqw);

        //重新设置dishDto中的Flavors属性。
        dishDto.setFlavors(list);
        //返回dishDto
        return dishDto;
    }


    /**
     * 修改菜品表，同时修改口味表
     * @param dishDto
     */
    @Override
    public void update(DishDto dishDto) {
        //修改菜品表
        this.updateById(dishDto);
        //清理当前菜品对应口味表格
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(queryWrapper);
        //添加前端传过来的口味表
        List<DishFlavor> flavors = dishDto.getFlavors();
        Long id = dishDto.getId();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(id);
        }
        dishFlavorService.saveBatch(flavors);
    }



}
